import baseUrl from "./url.js"
let is_open_socket = false //避免重复连接
let timeout= 2000 //多少秒执行心跳检测
let heartbeatInterval= null //检测服务器端是否还活着
let reconnectTimeOut= null //重连之后多久再次重连
var socketTask = null
let token = uni.getStorageSync("token")

// 进入这个页面的时候创建websocket连接【整个页面随时使用】
export function connectSocketInit() {
	if(is_open_socket) return
    socketTask = uni.connectSocket({
        url: `${baseUrl.socketUrl}?token=${token}`,
		header: {
			"token": token
		},
		success:()=>{
		    console.log("正准备建立websocket中...");
		    // 返回实例
		    return socketTask
		}
    })
	
    uni.onSocketOpen(() => {
        console.log("WebSocket连接正常！");
        clearTimeout(reconnectTimeOut)
        clearInterval(heartbeatInterval)
        is_open_socket = true;
        start();
    })

    // 监听连接失败
    uni.onSocketError(() => {
		console.log('WebSocket连接打开失败，请检查！');
		is_open_socket = false;
		reconnectTimeOut = setTimeout(()=>{
			reconnect();
		},2000)
    });
	
	// 监听websocket关闭
	uni.onSocketClose(()=> {
		console.log('WebSocket 已关闭！');
		is_open_socket = false
		// reconnectTimeOut = setTimeout(()=>{
		// 	reconnect();
		// },2000)
	});
}

//发送消息
export function send(value){
    uni.sendSocketMessage({
        data: value
    });
}


//开启心跳检测
function start(){
    heartbeatInterval = setInterval(()=>{
        send('PING');
    },timeout)
}

//重新连接
function reconnect(){
    //停止发送心跳
    clearInterval(heartbeatInterval)
	clearTimeout(reconnectTimeOut)
    //如果不是人为关闭的话，进行重连
    if(!is_open_socket){
        connectSocketInit();
    }
}

// 关闭长链接
export function removeWebsocket(){
	console.log("退出登录，关闭websocket")
    clearInterval(heartbeatInterval)
    clearTimeout(reconnectTimeOut)
    is_open_socket = false
    heartbeatInterval = null 
    reconnectTimeOut = null
    uni.closeSocket()
}




